package com.oujia.cloud.cloudcommon.bean.sender;


import com.oujia.cloud.cloudcommon.bean.config.RabbitMqConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Component(value = "logSender")
public class LogSender implements RabbitTemplate.ConfirmCallback {

    private static final Logger LOGGER = LoggerFactory.getLogger(LogSender.class);

    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RabbitMqConfig rabbitMqConfig;

    /**
     * 构造方法注入
     */
    @Autowired
    public LogSender(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
        this.rabbitTemplate.setConfirmCallback(this); //rabbitTemplate如果为单例的话，那回调就是最后设置的内容
    }

    public void sendMsg(Object msg) {
        LOGGER.info("发送消息到queue: queue={}, msg={}", rabbitMqConfig.getQueueLoge(), msg);
        CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
        rabbitTemplate.convertAndSend(rabbitMqConfig.getTopicExchangeName(),
                rabbitMqConfig.getRoutingKeyLog(), msg, correlationId);

    }

    /**
     * 回调
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        LOGGER.debug("回调消息id:" + correlationData);
        if (ack) {
            LOGGER.debug("消息发送确认成功");
        } else {
            LOGGER.debug("消息发送确认失败:" + cause);

        }
    }

}  